﻿function w(s) {
    var txt = document.getElementById('formula');
    if (document.selection) {
        txt.focus();
        sel = document.selection.createRange();
        sel.text = s;
        txt.focus();
    }
    else {
        var iStart = txt.selectionStart;
        var iEnd = txt.selectionEnd;
        var scrollTop = txt.scrollTop;
        txt.value = txt.value.substring(0, iEnd) + s + txt.value.substring(iEnd, txt.value.length);
        this.focus();
        txt.selectionStart = iStart + s.length;
        txt.selectionEnd = iEnd + s.length;
        txt.scrollTop = scrollTop;
    }

}

function createExpression(formula) {
    var exp = formula;
    var select = document.getElementsByTagName('select')[0];
    for (var i = select.options.length - 1; i >= 0; i--) {
        var item = select.options[i];
        exp = exp.replace(new RegExp(item.text, 'g'), 'FTargetNo' + item.value + '');
    }
    exp = exp.replace(/ = /g, ' = ');
    exp = exp.replace(/\r\n/g, '');
    exp = exp.replace(/并且/g, ' and  ');
    exp = exp.replace(/或者/g, ' or ');
    exp = exp.replace(/否则/g, ',');
    exp = exp.replace(/则/g, ',');
    return exp;
}

function OK() {
    var formula = document.getElementById('formula').value;
    var expression = createExpression(formula);
    var Type = $("#hdType").val();
    var FMonth = $("#hdFMonth").val();
    var FReportNo = $("#hdFReportNo").val();
    var FYear = $("#hdFYear").val();
    var FComputeDesc = $("#u99").val();
    var FFormulaID = $("#hdFFormulaID").val();
    var FSeq = $("#u96").val();
    $.ajax({
        type: 'POST',
        url: rootPath + '/SingleTableFormula/Save',
        data: { fFormulaID: FFormulaID, type: Type, fComputeDesc: FComputeDesc, fComputeExpression: expression, fComputeFormula: formula, fMonth: FMonth, fReportNo: FReportNo, fYear: FYear, fSeq: FSeq },
        success: function (result) {
            if (result == "ok") {
                parent.codeOK();
            } else if (result == "error") {
                alert('公式有误，请重新编辑！\r\n');
            }
            else {
                alert('公式有误，请重新编辑！\r\n');
            }
        }
    });
}


document.getElementsByTagName('select')[0].onclick = function () { if (this.selectedIndex >= 0) w(this.options[this.selectedIndex].text) };
var btns = document.getElementsByTagName('input');
for (var i = 0; i < btns.length; i++) {
    if (btns[i].value.indexOf('确定') > -1) {
 
    }
    else if (btns[i].value.indexOf('清空') > -1) {
        btns[i].onclick = function () { document.getElementById('formula').value = ''; };
    }

    else if (btns[i].value.indexOf('如果') > -1) {
        btns[i].onclick = function () { w('{如果  则\n\n 否则\n\n}') };
    }
    else if (btns[i].type == "text") { 
       
    }
    else {
        btns[i].onclick = function () { w(this.value) };
    }

}
